package com.allen.study.domain.utils.security;

import com.allen.study.test_common.constant.CacheConstants;
import com.allen.study.test_common.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: SecurityUtil
 * @Author: AllenSun
 * @Date: 2025/3/18 21:38
 */
@Component
@Slf4j
public class SecurityUtil {

    @Autowired
    private RedisUtils redisUtils;

    private int maxRetryCount = CacheConstants.PASSWORD_MAX_RETRY_COUNT;

    private Long lockTime = CacheConstants.PASSWORD_LOCK_TIME;

    // 失败次数递增（原子操作）
    public int incrementFailureCount(String username) {
        String retryCountKey = CacheConstants.PWD_ERR_CNT_KEY + username;
        redisUtils.incr(retryCountKey,1);
        redisUtils.expire(retryCountKey, 10*60); // 失败记录保留10分钟

        // Integer retryCount = (Integer) redisUtils.get(retryCountKey);
        // // 如果是null表示密码错误次数为0
        // if (retryCount == null) {
        //     retryCount = 0;
        // }
        // 如果密码错误次数大于等于5次，报错
        Integer retryCount = (Integer)redisUtils.get(retryCountKey);
        Integer maxRetryCountVal = Integer.valueOf(maxRetryCount).intValue();
        if (retryCount >= maxRetryCountVal) {
            lockAccount(username);
        }
        return maxRetryCountVal-retryCount;

    }

    // 检查是否锁定
    public boolean isAccountLocked(String username) {
        String lockKey = CacheConstants.USER_LOGIN_LOCK + username;
        Long expireTime = redisUtils.getExpire(lockKey);
        return expireTime != null && expireTime > 0;
    }

    public long getLockLeftTime(String username) {
        String lockKey = CacheConstants.USER_LOGIN_LOCK + username;
        Long expireTime = redisUtils.getExpire(lockKey);

        return expireTime;
    }

    // 执行账户锁定
    public void lockAccount(String username) {
        String lockKey = CacheConstants.USER_LOGIN_LOCK + username;
        Long lockTime = 5*60l;
        redisUtils.set(lockKey, System.currentTimeMillis());
        redisUtils.expire(lockKey, lockTime); // 锁定5分钟
        clearFailureCount(username);
        String errMsg = String.format("密码输入错误%s次，帐户锁定%s分钟", maxRetryCount, 5);
        log.info(errMsg);
    }

    public void clearFailureCount(String username) {
        String retryCountKey = CacheConstants.PWD_ERR_CNT_KEY + username;
        redisUtils.del(retryCountKey);
    }


}
